/* 
  题目3：完成 deepGet 函数，给它传入一个对象和字符串，字符串表示对象深层属性的获取路径，可以深层次获取对象内容：
*/
const deepGet = (obj, prop) => {
    // TODO: 在此处完善代码
    let target = undefined
    /* 
        1. 分割prop获取访问路径
    */
    let path = prop.split('.')
    // console.log(path);
    target = path.reduce((pre, cur) => {
        // console.log('pre', pre);
        // console.log('cur', cur);
        // 2. 访问传入对象
        if (pre) {
            if (cur.indexOf('[') !== -1) {
                // 存储数组索引
                let index = undefined
                index = cur.substring(cur.indexOf("[")+1,cur.indexOf("]"));
                // console.log('index', index);
                cur = cur.substr(0, cur.indexOf("["));
                // console.log('cur1', cur);
                return pre[cur][index]
            }
            return pre[cur]
        } else {
            return undefined
        }
    }, obj)
    console.log('target', target);
    return target
}



/** 以下为测试代码 */
deepGet({
    school: {
        student: { name: 'Tomy' },
    },
}, 'school.student.name') // => 'Tomy'

deepGet({
    school: {
        students: [
            { name: 'Tomy' },
            { name: 'Lucy' },
        ],
    }
}, 'school.students[1].name') // => 'Lucy'

// 对于不存在的属性，返回 undefined
deepGet({ user: { name: 'Tomy' } }, 'user.age') // => undefined
deepGet({ user: { name: 'Tomy' } }, 'school.user.age') // => undefined
